import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Http } from '@angular/http';
import { HttpRequest } from "../../../../service/httpRequest";
import { NotiService } from "../../../../service/noti.service";
import { ModalDirective } from 'ng2-bootstrap/modal';
declare let require:any;
let Base64 = require('../../../../../assets/js/Base64');
declare let $:any;


const zh = {TAB1_HEAD1:'变频器监控', TAB2_HEAD1:'监控界面', RUN_STATE_1:'运行', RUN_STATE_2:'正转', RUN_STATE_3:'正常', RUN_STATE_4:'基极封锁', TARGET_FREQUENCY:'目标频率',
  FEEDBACK_FREQUENCY:'反馈频率', INVERTER_INFO:'变频器信息', EDIT:'编辑', TAB1_TR1_TD1:'变频器品牌',TAB1_TR1_TD2:'新时达', TAB1_TR2_TD1:'变频器型号',
  TAB1_TR3_TD1:'变频器额定功率', TAB1_TR4_TD1:'变频器额定电压', TAB1_TR5_TD1:'变频器额定电流', TAB1_TR6_TD1:'变频器额定频率', TAB1_TR7_TD1:'变频器硬件版本',
  TAB1_TR8_TD1:'变频器软件版本', TAB1_TR9_TD1:'变频器版本号', MOTOR_INFO:'电机信息', TAB2_TR1_TD1:'电机品牌', TAB2_TR2_TD1:'电机型号', TAB2_TR3_TD1:'电机额定功率',
  TAB2_TR4_TD1:'电机额定电压', TAB2_TR5_TD1:'电机额定电流', TAB2_TR6_TD1:'电机额定频率', TAB2_TR7_TD1:'电机转速', TAB2_TR8_TD1:'电机级数', TAB2_TR9_TD1:'电机额定转矩',
  MONITOR_DATA:'监控数据', USER_DEFINED:'自定义', TAB3_TR1_TD1:'给定速度',TAB3_TR1_TD2:'输出电压', TAB3_TR2_TD1:'反馈速度',TAB3_TR2_TD2:'输出转速',
  TAB3_TR3_TD1:'驱动器效率',TAB3_TR3_TD2:'输出转矩', TAB3_TR4_TD1:'输出电流',TAB3_TR4_TD2:'运行状态', TAB3_TR5_TD1:'母线电压',TAB3_TR5_TD2:'散热器温度',
  INPUT_STATUS:'输入口状态',OUTPUT_STATUS:'输出口状态', FAULT_RECORD:'故障记录',READ_FAULT_INFO:'读取故障',DETAILS:'详细信息', TAB4_TD1:'序号',
  TAB4_TD2:'故障代码', TAB4_TD3:'故障名称', TAB4_TD4:'序号', TAB4_TD5:'故障代码', TAB4_TD6:'故障名称', TAB2_HEAD:'参数查询',
  PARAM_BTN:'获取参数', PARAM_INFO:'参数信息', LOADING:'数据读取中'
};

const en = {TAB1_HEAD1:'Inverter Monitoring', TAB2_HEAD1:'Monitor State', RUN_STATE_1:'Run', RUN_STATE_2:'Forward', RUN_STATE_3:'Normal',
  RUN_STATE_4:'Base Lockout', TARGET_FREQUENCY:'Target Frequency', FEEDBACK_FREQUENCY:'Feedback Frequency', INVERTER_INFO:'Information of the Inverter',
  EDIT:'edit', TAB1_TR1_TD1:'Inverter Brand', TAB1_TR1_TD2:'STEP', TAB1_TR2_TD1:'Inverter Model', TAB1_TR3_TD1:'Inverter Rated Power',
  TAB1_TR4_TD1:'Inverter Rated Voltage', TAB1_TR5_TD1:'Inverter Rated Current', TAB1_TR6_TD1:'Inverter Rated Frequency', TAB1_TR7_TD1:'Inverter Hardware Version',
  TAB1_TR8_TD1:'Inverter Software Version', TAB1_TR9_TD1:'Inverter Version Number', MOTOR_INFO:'Information of the Motor', TAB2_TR1_TD1:'Motor Brand',
  TAB2_TR2_TD1:'Motor Model', TAB2_TR3_TD1:'Motor Rated Power', TAB2_TR4_TD1:'Motor Rated Voltage', TAB2_TR5_TD1:'Motor Rated Current',
  TAB2_TR6_TD1:'Motor Rated Frequency', TAB2_TR7_TD1:'Motor Rotation Speed', TAB2_TR8_TD1:'Motor Poles', TAB2_TR9_TD1:'Motor Rated Torque',
  MONITOR_DATA:'Monitor Data',USER_DEFINED:'User defined', TAB3_TR1_TD1:'Given speed',TAB3_TR1_TD2:'Output voltage', TAB3_TR2_TD1:'Feedback speed',TAB3_TR2_TD2:'Output speed',
  TAB3_TR3_TD1:'Driver efficiency',TAB3_TR3_TD2:'Output torque', TAB3_TR4_TD1:'Output current',TAB3_TR4_TD2:'Operation state', TAB3_TR5_TD1:'Bus voltage',TAB3_TR5_TD2:'Radiator temperature',
  INPUT_STATUS:'Input status',OUTPUT_STATUS:'Output status', FAULT_RECORD:'Fault Record',READ_FAULT_INFO:'Read the fault information',DETAILS:'Details',
  TAB4_TD1:'No.', TAB4_TD2:'Fault code', TAB4_TD3:'Fault name', TAB4_TD4:'No.', TAB4_TD5:'Fault code', TAB4_TD6:'Fault name', TAB2_HEAD:'Parameters',
  PARAM_BTN:'GetParameters', PARAM_INFO:'Parameters Information', LOADING:'Loading'
};
@Component({
  selector: 'app-single-monitor',
  templateUrl: './single-monitor.component.html',
  styleUrls: [
    '../../../../../assets/css/convertor-v1.1.css',
    '../../../../../assets/css/hzw-city-picker.css',
    './single-monitor.component.css']
})
export class SingleMonitorComponent implements OnInit {
  _code_kv = {
    0:'无故障',
    1:'模块过流保护',2:'ADC故障',3:'散热器过热',4:'制动单元故障',5:'熔丝断故障',6:'输出过力矩',
    7:'速度偏差',8:'母线过压保护',9:'母线欠电压',10:'输出缺相',11:'电机低速过流',12:'编码器故障',
    13:'停车时检测到电流',14:'运行中速度反向',15:'停车时检测到速度',16:'电机相序错',17:'同向超速',18:'反向超速',19:'UVW编码器相序错误',
    20:'编码器通信故障',21:'abc过电流',22:'制动器检测故障',23:'输入过电压',24:'UVW编码器断线',25:'备用',26:'编码器无自学习',27:'输出过电流',
    28:'Sincos编码器故障',29:'输入缺相',30:'超速保护',31:'电机高速过电流',32:'接地保护',33:'电容老化',
    34:'外部故障',35:'输出不平衡',36:'参数设置错误',37:'电流传感器故障',38:'制动电阻短路',39:'电流瞬时值过大',
    40:'输出接触器故障',41:'抱闸检测故障',42:'IGBT短路故障',43:'通讯故障',44:'输入电源不正常',45:'I2t瞬时值过流',
    46:'I2t有效值过流',47:'模拟输入异常',48:'温度采样断线',49:'PT检测故障',50:'Humidity故障',51:'运行电流异常',
    52:'电机PTC过热报警'
  };
  _code_kv_en = {
    0:'No fault',
    1:'Module over-current protection',2:'ADC fault',3:'Heatsink overheat',4:'Braking unit failure',5:'Blown fuse failure',6:'Over torque output',
    7:'Speed deviation',8:'Bus over voltage protection (running at constant speed)',9:'Bus undervoltage',10:'Loss of output phase',11:'Motor over current at low speed (during constant speed)',12:'Encoder failure',
    13:'Current detected at stopping',14:'Reversed speed during operation',15:'Speed detected at stopping',16:'Wrong motor phase',17:'Over speed in the same direction (in maximum allowed speed)',18:'Over speed in opposite direction (in maximum allowed speed)',19:'UVW encoder wrong phase order',
    20:'Encoder communication fault',21:'abc over current (3 phase instantaneous value)',22:'Brake detection fault',23:'Input over-voltage',24:'UVW encoder wire broken',25:'Reserved for future use',26:'Encoder no self-learning',27:'Output over current (valid value)',
    28:'SIN/COS encoder fault',29:'Loss input phase',30:'Over speed protection (exceed maximum protected speed limit)',31:'Over current at motor high speed',32:'Grounding protection',33:'Capacitor aged',
    34:'External fault',35:'Unbalance output',36:'Wrong parameter setting',37:'Current sensor fault',38:'Brake resistor short',39:'Too high instantaneous current',
    40:'KMY detection fault',41:'Brake switch detection fault',42:'IGBT short circuit protection',43:'Communication fault',44:'The input power supply is abnormal',45:'I2t instantaneous over current protection',
    46:'I2t valid over current protection',47:'Abnormal analog input',48:'Temperature sampling disconnection',49:'PT detection fault',50:'Humidity fault',51:'Abnormal running output current',
    52:'Motor PTC overheat warning'
  };

  lan:any;
  cmdtype = '';
  msgfaultdata={};

  aaData1;
  aaData2;
  aaData1_en;
  aaData2_en;

  @ViewChild('myModal') public myModal:ModalDirective;
  buttonType:number;
  disabled:string = "";
  oo:any;
  selectLang:string = '';
  deviceId:string = '';
  private gizwitsNotiWs:any;
  private eventType = ['device.status.kv','device.status.raw'];

  constructor(private activeRoute:ActivatedRoute,
              private httpRequest:HttpRequest,
              private noti:NotiService,
              private http:Http) { }

  ngOnInit() {

    this.activeRoute.params.subscribe(
      params=>{
        this.deviceId = params['deviceId'].replace('|','/');

        let p = this.deviceId.split('/');
        this.gizwitsNotiWs = this.noti.init(p[0].toLocaleLowerCase(),[p[1]],this.eventType,this.onEvent,this);
        this.gizwitsNotiWs.connect();
        this.getData();
      }
    );
    this.lan = localStorage.getItem("language") == 'en' ? en : zh;

  }

  getData(){
    this.http.get('assets/convertorparam.json').subscribe(data =>{
      this.handleData(data.json(),'参数名称','操作当前值');
    });


    this.http.get('assets/convertorparamen.json').subscribe(data =>{
      this.handleData(data.json(),'Parameters Name','Operating Current Value')
    });



  }

  handleData(data,p1,p2){
    //console.log(data)
    let xhtml ="";
    if (data) {
      $.each(data,function(i,n){
        let tableHtml = "<div class='panel panel-default'>"
          + "<div class='panel-heading'>"
          +n.name+"</div>"
          + "<div class='panel-body' >"
          + "<table class='table table-hover'style='margin-top:-8px'>"
          + "<tr style='border-top:0px'><th width='50%;' style='border-top:0px'>"+p1+"</th><th style='border-top:0px'>"+p2+"</th></tr>";
        $.each(n.uxcs,function(j,m){
          let key = m.num;
          tableHtml +="<tr>"
            + "<td >" + m.name +"</td>"
            +"<td ><span class='"+ m.num +"'>--</span>" + m.unit +"</td>"
            +"</tr>";
        });
        tableHtml += "</table></div></div>";
        xhtml += tableHtml;
      });
    }
    $("#parainfo2en").empty();
    $("#parainfo2en").append(xhtml);
  }


  openModal(type:number){
    this.buttonType = type;

    this.myModal.show();
    if(type == 1) this.getDefineData();
    if(type == 2) this.getFaultData();
  }

  getDefineData(){
    this.oo = {selected1:'',selected2:''}
  }
  getFaultData(){
    let lanData,code;
    if(localStorage.getItem("language") == 'en') code = this._code_kv;
    else code = this._code_kv_en;

    this.oo = new Array(8);
    for(let i=0;i<8;i++){
      let k1 = "fault"+ i + "_code";
      let k2 = "fault" + i + "_name";
      let k3 = "fault" + i + "_real_speed";
      let k4 = "fault" + i + "_given_speed";
      let k5 = "fault" + i + "_bus_voltage";
      let k6 = "fault" + i + "_current";
      this.oo[i] = {};
      this.oo[i]['fault_code'] = this.msgfaultdata[k1] ? this.msgfaultdata[k1] : '';
      this.oo[i]['fault_name'] = code[this.msgfaultdata[k2]] ? code[this.msgfaultdata[k2]] : '';
      this.oo[i]['fault_real_speed'] = this.msgfaultdata[k3] ? this.msgfaultdata[k3] : '';
      this.oo[i]['fault_given_speed'] = this.msgfaultdata[k4] ? this.msgfaultdata[k4] : '';
      this.oo[i]['fault_bus_voltage'] = this.msgfaultdata[k5] ? this.msgfaultdata[k5] : '';
      this.oo[i]['fault_current'] = this.msgfaultdata[k6] ? this.msgfaultdata[k6] : '';
    }
  }


  onEvent(msg,that){
    // if(msg==null||msg==undefined){
    //    setTimeout("pulishstate()", 5000)
    // }
    //console.log(msg);
    if(msg.event_type=="device_status_raw"){
      //console.log(msg.data.raw);
      let tdata = Base64.Base64.decode(msg.data.raw.replace(/[\n]/ig,''));
      //console.log(tdata);
      let zdata = JSON.parse(tdata);
      //console.log(zdata);
      that.msgfaultdata = {};
      that.msgfaultdata_en = {};
      if(that.cmdtype=='fault'){
        that.msgfaultdata = zdata;
      }

      for(let key in zdata){
        $("#"+key).text(zdata[key]);
        if(key.lastIndexOf("_code") > 0){
          for(let i=0;i<8;i++){
            let kl = "fault" + i + "_code";
            let kl1 = "fault" + i + "_name";
            $("#"+kl1).text(that._code_kv[ zdata[kl] ] );
          }
        }
      }
      if(that.cmdtype=='fault_en'){
        that.msgfaultdata_en = zdata;
        for(let key in zdata){
          $("#"+key).text(zdata[key]);
          if(key.lastIndexOf("_code") > 0){
            for(let i=0;i<8;i++){
              let kl = "fault" + i + "_code";
              let kl1 = "fault" + i + "_name";

              $("#"+kl1).text(that._code_kv_en[ zdata[kl] ] );
            }
          }
        }
      }
      if(that.cmdtype=='param' ||　that.cmdtype=='param_en'){
        that.getparaminfo(zdata);
      }

    }
    if(msg.event_type=="device_status_kv"){
      msg = msg.data;
      for(let key in msg){

        if(parseInt(msg[key])==msg[key]){
          $("#"+key).text(Number(msg[key]));
        }else{
          $("#"+key).text(Number(msg[key]).toFixed(2));
        }

        if(that.aaData1!= undefined){
          if(that.aaData1.id==key){
            if(parseInt(msg[key])==msg[key]){
              $("#definedata1").text(Number(msg[key]))
            }else{
              $("#definedata1").text(Number(msg[key]).toFixed(2));
            }

          }
        }

        if(that.aaData1_en!= undefined){
          if(that.aaData1_en.class==key){
            if(parseInt(msg[key])==msg[key]){
              $(".definedata1").text(Number(msg[key]))
            }else{
              $(".definedata1").text(Number(msg[key]).toFixed(2));
            }
          }
        }

        if(that.aaData2!= undefined){
          if(that.aaData2.id==key){
            if(parseInt(msg[key])==msg[key]){
              $("#definedata2").text(Number(msg[key]))
            }else{
              $("#definedata2").text(Number(msg[key]).toFixed(2));
            }
          }
        }

        if(that.aaData2_en!= undefined){
          if(that.aaData2_en.class==key){
            if(parseInt(msg[key])==msg[key]){
              $(".definedata2").text(Number(msg[key]))
            }else{
              $(".definedata2").text(Number(msg[key]).toFixed(2));
            }
          }
        }


        if(key=="run_state_1" && msg[key]=="0"){
          $("#"+key).removeClass("green");
          $("#"+key).addClass("gray");
        }

        if(key=="run_state_1" && msg[key]=="1"){
          $("#"+key).removeClass("gray");
          $("#"+key).addClass("green");
        }

        if(key=="run_state_2" && msg[key]=="0"){
          $("#"+key).removeClass("green");
          $("#"+key).addClass("blue");
        }

        if(key=="run_state_2" && msg[key]=="1"){
          $("#"+key).removeClass("gray");
          $("#"+key).addClass("green");
        }

        if(key=="run_state_3" && msg[key]=="1"){
          $("#"+key).removeClass("gray");
          $("#"+key).addClass("green");

        }

        if(key=="run_state_3" && msg[key]=="0"){
          $("#"+key).removeClass("green");
          $("#"+key).addClass("gray");
        }

        if(key=="run_state_4" && msg[key]=="1"){
          $("#"+key).removeClass("green");
          $("#"+key).addClass("red");
        }

        if(key=="run_state_4" && msg[key]=="0"){
          $("#"+key).removeClass("red");
          $("#"+key).addClass("green");
        }

        if(key=="given_speed"){
          $("#"+key).text(Number(msg[key]).toFixed(2));
          $("#given_speed1").text(Number(msg[key]).toFixed(2));
          $("#feedback_speed2").text(Number(msg[key]).toFixed(2));

        }

        if(key=="feedback_speed"){
          $("#feedback_speed1").text(Number(msg[key]).toFixed(2));

        }

        for(let j=0;j<7;j++){

          if(key=="X"+j && msg[key]=="0"){
            $("#"+key).removeClass("green");
            $("#"+key).addClass("gray")
            $("#"+key).text("X" + j);
          }

          if(key=="X"+j && msg[key]=="1"){
            $("#"+key).removeClass("gray");
            $("#"+key).addClass("green")
            $("#"+key).text("X" + j);
          }

        }


        for(let m=1;m<5;m++){

          if(key=="K"+m && msg[key]=="0"){
            $("#"+key).removeClass("blue");
            $("#"+key).addClass("gray")
            $("#"+key).text("K" + m);
          }
          if(key=="K"+m && msg[key]=="1"){
            $("#"+key).removeClass("gray");
            $("#"+key).addClass("blue")
            $("#"+key).text("K" + m);
          }
        }



        for(let n=0;n<2;n++){
          if(key=="Y"+n && msg[key]=="0"){
            $("#"+key).removeClass("blue");
            $("#"+key).addClass("gray")
            $("#"+key).text("Y" + n);
          }
          if(key=="Y"+n && msg[key]=="1"){
            $("#"+key).removeClass("gray");
            $("#"+key).addClass("blue")
            $("#"+key).text("Y" + n);
          }
        }
      }

    }
  }
  getparaminfo(paramaterdata){
    $("#loadingdata").hide();
    if(paramaterdata){
      $("#parainfo2").show();
      $("#parainfo2en").show();
    }
    for(let key in paramaterdata){
      $("#"+key).text(paramaterdata[key]);
    }

  }

  getParams(type){
    this.cmdtype = type;
    let t = this.deviceId.split('/');
    this.httpRequest.sendPost('common/sendCommand',{
      product_id: t[0],
      mac: t[1],
      command:"{\"attrs\":{\"cmd\":\"func_fault\"}}"
    }).subscribe(res=>{},err=>{})
  }

  getFault(type){
    this.cmdtype = type;
    let t = this.deviceId.split('/');
    this.httpRequest.sendPost('common/sendCommand',{
      product_id: t[0],
      mac: t[1],
      command:"{\"attrs\":{\"cmd\":\"func_parameter\"}}"
    }).subscribe(res=>{},err=>{})
  }
}
